function RealTypeOf(v) {
  if (typeof(v) == "object") {
    if (v === null) return "null";
    if (v.constructor == (new Array).constructor) return "array";
    if (v.constructor == (new Date).constructor) return "date";
    if (v.constructor == (new RegExp).constructor) return "regex";
    return "object";
  }
  return typeof(v);
}

jPersist = window.jPersist = function(appName,debug){
	this.debug = (!debug)?false:true;
	if (!appName) {
		this.log("No AppName given!","error");
	} else {
		this.ns = appName;
		this.log("Started!","info");
	}
}
jPersist.prototype = window.jPersist.prototype = ({
	ns: '',
	debug: false,
	log: function (message,level){
		var level = (!level)?"":level;
		if (this.debug == true){
			if (typeof(message) == "string"){
				var msg = (!this.ns)?"[jPersist] "+message:"[jPersist:"+this.ns+"] "+message;
			}
			switch (level.toLowerCase()){
				case "warn":
					console.warn(msg);
					break;
				case "info":
					console.info(msg);
					break;
				case "error":
					console.error(msg);
					break;
				default:
					console.log(msg);
					break;
			}
		}
	},
	get: function(name){
		var rawVal = window.localStorage.getItem("jPersist:"+this.ns+":"+name);
		var splitVal = rawVal.split("::");
		var type = splitVal[0];
		var value = splitVal[1];
		switch(type.toLowerCase()){
			case "obj":
				var ret = JSON.parse(value);
				break;
			case "arr":
				var ret = JSON.parse(value);
				break;
			case "regexp":
				var ret = RegExp(value);
				break;
			case "date":
				var ret = Date(value);
				break;
			case "str":
				var ret = String(value);
				break;
			case "num":
				var ret = Number(value);
				break;
			case "bool":
				var ret = Boolean(value);
				break;
			case "null":
				var ret = null;
				break;
			case "func":
				var ret = Function(unescape(value));
				break;
			default:
				var ret = unescape(value);
		}
		return ret;
	},
	set: function(name,value){
		switch(RealTypeOf(value)){
			case "object":
				var ret = "obj::"+JSON.stringify(value);
				break;
			case "array":
				var ret = "arr::"+JSON.stringify(value);
				break;
			case "regex":
				var ret = "regexp::"+value.toString();
				break;
			case "date":
				var ret = "date::"+value.toString();
				break;
			case "string":
				var ret = "str::"+value.toString();
				break;
			case "number":
				var ret = "num::"+value.toString();
				break;
			case "boolean":
				var ret = "bool::"+value.toString();
				break;
			case "null":
				var ret = "null::null";
				break;
			case "function":
				var ret = "func::"+escape(value.toString());
				break;
			default:
				var ret = escape(value.toString());
		}
		window.localStorage.setItem("jPersist:"+this.ns+":"+name,ret);
	},
});